package mylog

import (
  "dog.com"
  "github.com/op/go-logging"
  "fmt"
  "os"
  "sync"
)

/******************全局变量**********************/

var logFileP *os.File
var once sync.Once
var Log = logging.MustGetLogger("another")

var format = logging.MustStringFormatter(
	`%{time:15:04:05.000} %{shortfunc} ▶ %{level:.4s} %{id:03x} %{message}`,
)

/******************全局变量**********************/

//var log = logging.MustGetLogger("another")

func DogError(str string) {
  fmt.Println("this is DogError!!!!!!!! = ", str)
  Log.Error(str)
  Log.Error("wo jiu buxinle!")
}

func GetLogger() *logging.Logger {
  // return logging.MustGetLogger("example")
  return Log
}


func initLog( logFunction func(... interface{}), arg ...interface{}){
  //获取全局系统配置变量 config
  config := dog.ConfigFactory()

  // Open Log File
  logFileP, err := os.OpenFile(config.Logfile, 0 , os.ModeAppend)
  defer logFileP.Close()
  if err != nil {
      fmt.Println("open file ", config.Logfile,  " fail !")
      return
  }

	// For demo purposes, create two backend for os.Stderr.
	// backend1 := logging.NewLogBackend(os.Stderr, "", 0)
  // 装饰起模式
	backend1 := logging.NewLogBackend(logFileP, "", 0)
	// backend2 := logging.NewLogBackend(os.Stderr, "", 0)
	backend2 := logging.NewLogBackend(logFileP, "", 0)

	// For messages written to backend2 we want to add some additional
	// information to the output, including the used log level and the name of
	// the function.
	backend1Formatter := logging.NewBackendFormatter(backend1, format)

	// Only errors and more severe messages should be sent to backend1
	backend2Leveled := logging.AddModuleLevel(backend2)
	// backend1Leveled.SetLevel(logging.ERROR, "")
  //设置日志错误级别
  for _, logLevel := range config.LogLevel {
      fmt.Println("---------------logLevel = ", logLevel)
      switch logLevel {
          case "Error":
              backend2Leveled.SetLevel(logging.ERROR, "")
              break;
          case "Info":
              backend2Leveled.SetLevel(logging.INFO, "")
              break;
          default:
              fmt.Println("loglevel [", logLevel , "] format is error!")
      }
  }
	// Set the backends to be used.
  //这是是可变参数数量函数 可以设置多个 backend
	//logging.SetBackend(backend1Leveled, backend2Formatter)
	logging.SetBackend(backend1Formatter, backend2Leveled)


  Log.Error("this is 000000000000000001111!")
  logFunction(arg)
  //LogFactory(arg)
}

func LogFactory() {


  /* Open Log File
  logP, err := os.Create(config.Logfile)
  defer logP.Close()
  if err != nil {
      return
  }
  */

  //once.Do(initLog)
  initLog(Log.Error, "HelloWorld")
  initLog(Log.Debug, "HelloWorld-------------")

  Log.Error("this is 00000000000000000!")
  Log.Debug("this is 00000000000000000!")
}

func CreateLog(fileName string) (*logging.Logger) {
    return logging.MustGetLogger("another")
}
